using System;
using System.Xml;

namespace AleaClasses
{
	/// <summary>
	/// TAleaGraph is one Alea graph.
	/// </summary>
	public class TAleaGraph: TTrackEdits
	{
		private TLabels fLabels;
		private TNodes fNodes;
		private TNode fStartNode;

		private void Constructor(TLabels aLabels, TNodes aNodes, TNode aStartNode)
		{
			fLabels = aLabels;
			fNodes = aNodes;
			fStartNode = aStartNode;
		}

		public TAleaGraph()
		{
			Constructor(new TLabels(), new TNodes(), null);
			SetNeedsSave();
		}

		public TAleaGraph(TLabels aLabels, TNodes aNodes, TNode aStartNode)
		{
			Constructor(aLabels, aNodes, aStartNode);
			SetNeedsSave();
		}

		public TAleaGraph(XmlElement aAleaGraphElement)
        {
            LoadFromXml(aAleaGraphElement);
        }

        private void LoadFromXml(XmlElement aAleaGraphElement)
		{
			TLabels lLabels = null;
			TNodes lNodes = null;
			TNode lStartNode = null;

			XmlElement lSubElem = null;
			
			lSubElem = aAleaGraphElement.SelectSingleNode("Labels") as XmlElement;
			if (lSubElem != null)
			{
				lLabels = new TLabels(lSubElem);
			}

			lSubElem = aAleaGraphElement.SelectSingleNode("Nodes") as XmlElement;
			if (lSubElem != null)
			{
				lNodes = new TNodes(lSubElem, lLabels);
			}

			lSubElem = aAleaGraphElement.SelectSingleNode("StartNode") as XmlElement;
			if (lSubElem != null)
			{
				string lStartNodeCode = Convert.ToString(lSubElem.InnerText.Trim());
				lStartNode = lNodes.GetNodeByNodeCode(lStartNodeCode);
			}

			Constructor(lLabels, lNodes, lStartNode);

			ClearNeedsSave();
		}

        public TAleaGraph(string fileName)
        {
            XmlDocument lDoc = new XmlDocument();
            lDoc.Load(fileName);
            LoadFromXml(lDoc.ChildNodes[0] as XmlElement);
        }

        public XmlElement SaveToXml(XmlDocument aDoc)
		{
			XmlElement retval = null;
			XmlElement elem = null;

			retval = aDoc.CreateElement("AleaGraph");

			elem = Labels.SaveToXml(aDoc);
			if (elem != null)
				retval.AppendChild(elem);

			elem = Nodes.SaveToXml(aDoc);
			if (elem != null)
				retval.AppendChild(elem);

			if (StartNode != null)
			{
				elem = aDoc.CreateElement("StartNode");
				elem.InnerText = StartNode.NodeCode;
				retval.AppendChild(elem);
			}

			return retval;
		}

		public TLabels Labels
		{
			get
			{
				return fLabels;
			}
		}

		public TNodes Nodes
		{
			get
			{
				return fNodes;
			}
		}

		public TNode StartNode
		{
			get
			{
				return fStartNode;
			}
			set
			{
				if (fStartNode != value)
				{
					fStartNode = value;
					SetNeedsSave();
				}
			}
		}

		protected override bool ChildrenNeedSave()
		{
			return Labels.NeedsSave() || Nodes.NeedsSave();
		}

		protected override void ClearChildrenNeedsSave()
		{
			Labels.ClearNeedsSave();
			Nodes.ClearNeedsSave();
		}
	}
}
